/**
 * rsa 公钥加密， 默认不加密，开关打开时才执行加密逻辑
 * @param text {string} 明文
 * @return {string} 密文
 */
let encryptRsa = (text) => {
  if (process.env.VUE_APP_ENCRYPT_ENABLED === 'YES') {
    if (process.env.GULPFILE) { // gulpfile 测试
      const NodeRSA = require('node-rsa')
      const RSA = new NodeRSA(`-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvqgT1MSFh/l6sLZd2MtD
H7zWWpBPN7hnwzthdwnwllCGc1hxuH+iE7aRlpd4zumQXYhMd4mjLqoOcKUEwkwW
cY2vRsnOIEMhM5dGqTjo6g4iKcZhBu8buvQt/NZECbQfhlIKqRdL5SL8YLnK5CRH
q/siWHuwNG1gKkiPLSrrin3EPIczD7jR2fRC6J5DubPcSfa91AoscbFTTl8vWYKD
t6p9va0mjVvjPsCnIYMjlaelFsdE4bawcmROfVzSwgFfn1qhbZWH17FG28vXr2fh
2yDOu6oRQvSENY7xoRr7urpxYtz9CNQqPWFpwex93VQRF1+c+KcUdgJH845St+0F
GwIDAQAB
-----END PUBLIC KEY-----`, {encryptionScheme: 'pkcs1'})
      encryptRsa = text => RSA.encrypt(text, 'base64')
    } else {
      const {JSEncrypt} = require('jsencrypt')
      const RSA = new JSEncrypt()
      RSA.setPublicKey(process.env.VUE_APP_ENCRYPT_PUBLIC_KEY) // 设置公钥
      encryptRsa = text => RSA.encrypt(text)
    }
  } else {
    encryptRsa = text => text
  }
  return encryptRsa(text)
}

/**
 * rsa 公钥解密， 默认不加密，开关打开时才执行解密逻辑
 * @param text {string} 明文
 * @return {string} 密文
 */
let decryptRsa = (text) => {
  if (process.env.VUE_APP_ENCRYPT_ENABLED === 'YES') {
    if (process.env.GULPFILE) { // gulpfile 测试
      const NodeRSA = require('node-rsa')
      const RSA = new NodeRSA(`-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvqgT1MSFh/l6sLZd2MtD
H7zWWpBPN7hnwzthdwnwllCGc1hxuH+iE7aRlpd4zumQXYhMd4mjLqoOcKUEwkwW
cY2vRsnOIEMhM5dGqTjo6g4iKcZhBu8buvQt/NZECbQfhlIKqRdL5SL8YLnK5CRH
q/siWHuwNG1gKkiPLSrrin3EPIczD7jR2fRC6J5DubPcSfa91AoscbFTTl8vWYKD
t6p9va0mjVvjPsCnIYMjlaelFsdE4bawcmROfVzSwgFfn1qhbZWH17FG28vXr2fh
2yDOu6oRQvSENY7xoRr7urpxYtz9CNQqPWFpwex93VQRF1+c+KcUdgJH845St+0F
GwIDAQAB
-----END PUBLIC KEY-----`, {encryptionScheme: 'pkcs1'})
      decryptRsa = text => RSA.decryptPublic(text, 'utf8')
    } else {
      throw new Error('jsencrypt 不支持公钥解密')
      // const {JSEncrypt} = require('jsencrypt')
      // const RSA = new JSEncrypt()
      // RSA.setPublicKey(process.env.VUE_APP_ENCRYPT_PUBLIC_KEY) // 设置公钥
      // decryptRsa = text => RSA.decrypt(text)
    }
  } else {
    decryptRsa = text => text
  }
  return decryptRsa(text)
}

export default class Rsa {
  /**
   * rsa 公钥加密
   * @param text {string} 明文
   * @return {string} 密文
   */
  static encrypt(text) {
    return encryptRsa(text)
  }

  /**
   * rsa 公钥解密
   * @param text {string} 密文
   * @return {string} 明文
   */
  static decrypt(text) {
    return decryptRsa(text)
  }
}
